package com.yun.zhong.fu.sharecenter.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.github.pagehelper.PageInfo;
import com.yun.zhong.fu.sharecenter.annoation.CheckLog;
import com.yun.zhong.fu.sharecenter.domain.ShareDto;
import com.yun.zhong.fu.sharecenter.domain.UserDto;
import com.yun.zhong.fu.sharecenter.entity.Share;
import com.yun.zhong.fu.sharecenter.feginclinet.TestBaiduFeign;
import com.yun.zhong.fu.sharecenter.feginclinet.TestUserCenterFegin;
import com.yun.zhong.fu.sharecenter.jwt.JwtOperator;
import com.yun.zhong.fu.sharecenter.service.ShareService;
import io.jsonwebtoken.Claims;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author RenPu
 * @Date 2020/12/28 16:31
 * @Version 1.0
 * @Description:
 **/

@RestController
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
@RequestMapping("/share")
public class ShareController {


    private final DiscoveryClient discoveryClient;

    private final ShareService shareService;

    private final JwtOperator jwtOperator;

    private final RestTemplate restTemplate;


    /**
     * @param id
     * @param ,@RequestHeader("X-Token") String token
     * @return
     * @RequestHeader("X-Token"):表明接受前端传来的token
     */
    @GetMapping("{id}")
    @CheckLog
    public ShareDto queryByIdShare(@PathVariable("id") Integer id) {
        return this.shareService.getById(id);
    }


    @GetMapping("test2")
    public List<ServiceInstance> test2() {
        List<ServiceInstance> instances = discoveryClient.getInstances("user-center");
        return instances;
    }


    @Autowired
    private TestUserCenterFegin testUserCenterFegin;


    /**
     * 测试feign传入多个参数的解决方法
     *
     * @param userDto
     * @return
     */
    @GetMapping("/testFegin")
    public UserDto testFeignParameter(UserDto userDto) {

        return testUserCenterFegin.testFeignParamter(userDto);

    }


    @Autowired
    private TestBaiduFeign testBaiduFeign;


    /**
     * 脱离ribbon，假如需要调用的服务没有在注册中心，feign的解决方案，在这以百度为例
     *
     * @return
     */
    @GetMapping("baidu")
    public String baiduIndex() {
        return testBaiduFeign.index();
    }


    @SentinelResource("hot")
    @GetMapping("/hot")
    public String hot(
            @RequestParam(required = false) String a,
            @RequestParam(required = false) String b) {
        return a + b;

    }


    /**
     * 配合测试feign多参数传入的解决方案
     *
     * @param
     * @return
     */
    @GetMapping("/makeToken")
    public String makeToken() {

        Map<String, Object> map = new HashMap<>(3);
        map.put("id", 1);
        map.put("title", "世界之巅");
        map.put("reason", "这是一个优秀的资源");
        String token = this.jwtOperator.generateToken(map);
        return token;
    }


    /**
     * 分页查询方法
     *
     * @param pageNo
     * @param pageSize
     * @param title
     * @return
     */
    @GetMapping("/q")
    public PageInfo<Share> pageMethond(@RequestParam(required = false, defaultValue = "1") Integer pageNo,
                                       @RequestParam(required = false, defaultValue = "10") Integer pageSize,
                                       @RequestParam(required = false) String title,
                                       @RequestHeader(value = "X-Token", required = false) String token) {
        //防止每页数据量过大，造成数据量过大
        if (pageSize > 100) {
            pageSize = 100;
        }

        Integer userId = null;
        if (StringUtils.isNotBlank(token)) {
            Claims claimsFromToken = jwtOperator.getClaimsFromToken(token);
            userId = (Integer) claimsFromToken.get("id");
        }


        return this.shareService.page(pageNo, pageSize, title, userId);
    }


    /**
     * 积分兑换指定ID的share
     *
     * @param id
     * @return
     */
    @GetMapping("/exchange/{id}")
    @CheckLog  //必须登录才能访问此接口
    public Share exchangeById(@PathVariable Integer id, HttpServletRequest request) {
        return this.shareService.exchangeById(id, request);
    }


    /**
     * 测试异构服务node.js可以在java服务中的调用
     *
     * @return
     */
    @GetMapping("/testNodeJs")
    public String testNodeJs() {
        return this.restTemplate.getForObject("http://wii", String.class);

    }
}
